package com.tongxin.van.frameworkcanary.base;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

import java.util.Stack;
/**
 *
 * author: VanyLiu
 * email: 13212674795@163.com
 * description: 活动管理工具类
 *
**/
public class ActivityManager {

    private static Stack<Activity> activityStack = new Stack<>();
    private static ActivityManager manager;

    private static Object object = new Object();

    private ActivityManager(){

    }

    public static ActivityManager getManager(){
        if(manager == null){
            synchronized (object){
                manager = new ActivityManager();
            }
        }
        return manager;
    }

    /**
     * 放
     * @param activity
     */
    public void pushActivity(Activity activity){
        if(activity != null){
            Log.i("ActivityManager", "activity = " + activity.getClass().getSimpleName());
            activityStack.add(activity);
        }
    }

    /**
     * 清除
     * @param activity
     */
    public void popActivity(Activity activity){
        if(activity != null){
            activity.finish();
            activityStack.remove(activity);
            activity = null;
        }
    }
    public void popActivity(Class clz){
        int i = 0;
        while (activityStack.size() > 0){
            Activity activity = activityStack.get(i);
            if(activity != null && activity.getClass().equals(clz)){
                popActivity(activity);
                break;
            }else {
                i++;
                if(i >= activityStack.size())
                    break;
            }
        }
    }


    /**
     * 获得栈顶activity
     * @return
     */
    public Activity currentActivity(){
        Activity activity = null;
        if(!activityStack.empty()){
            activity = activityStack.lastElement();
        }
        return activity;
    }

    /**
     * 退出所有activity
     */
    public void popAllActivity(){
        while (true){
            Activity activity = currentActivity();
            if(activity == null)
                break;

            popActivity(activity);
        }
    }

    /**
     * 保留传入的activity
     * @param clz
     */
    public void popAllActivityExceptOne(Class clz){
        while (true){
            Activity activity = currentActivity();
            if(activity == null)
                break;

            if (activity.getClass().equals(clz) )
                break;

            popActivity(activity);
        }
    }

    /**
     * 退出app
     * @param context
     */
    public void appExit(Context context) {
        try {
            popAllActivity();
            Runtime.getRuntime().exit(0);
        } catch (Exception e) {
            Runtime.getRuntime().exit(-1);
        }
    }
}
